﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Net;

namespace ServiceBase
{
    public static class GetBitmap
    {
        /// <summary>
        /// 获取某文件夹下的图片列表
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static Bitmap[] From_Folder(string dir)
        {
            List<string> pathList = new List<string>();
            string suffixStr = "*.jpg|*.png|*.jpeg|*.gif|*.bmp";
            foreach (string suffix in suffixStr.Split('|'))
            {
                foreach (string item in Directory.GetFiles(dir, suffix, SearchOption.TopDirectoryOnly))
                {
                    pathList.Add(item);
                }
            }
            List<Bitmap> list = new List<Bitmap>();
            foreach (string path in pathList)
            {
                list.Add(Form_FilePath(path));
            }
            return list.ToArray();
        }
        /// <summary>
        /// 加载一个磁盘上的图片文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Bitmap Form_FilePath(string path)
        {
            Bitmap map = new Bitmap(new MemoryStream(File.ReadAllBytes(path)));
            return map;
        }
        /// <summary>
        /// 加载一个http图片资源
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Bitmap From_URL(string url)
        {
            return DownImage(url);
        }

        /// <summary>
        /// 根据URL下载一张图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static Bitmap DownImage(string url)
        {
            try
            {
                WebRequest request = WebRequest.Create(url);
                request.Timeout = 3000;
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                Bitmap img = new Bitmap(responseStream);
                responseStream.Close();
                response.Close();
                return img;
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    if (response != null)
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)response;
                        switch (httpResponse.StatusCode)
                        {
                            case HttpStatusCode.RequestTimeout: break;
                            default: break;
                        }
                    }
                }
                return null;
            }
        }
    }
}
